package com.gene.tlonpo.service.remote.common.handler;

import com.gene.tlonpo.service.remote.common.enums.ModeEnum;
import com.gene.tlonpo.service.remote.common.model.DataDto;
import com.gene.tlonpo.service.remote.common.model.DataRespDto;
import com.gene.tlonpo.service.remote.common.protof.ProtofHeader;
import com.gene.tlonpo.service.remote.common.protof.TlonpoProtof;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author geneX
 * 通信编码器
 */
public class TlonpoNettyEncoder extends MessageToByteEncoder<Object> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        //协议组装
        ModeEnum modeEnum = getModeEnum(msg);

        ProtofHeader header = new ProtofHeader(modeEnum);

        TlonpoProtof protof = new TlonpoProtof(header, msg);

        protof.encode(out);
    }

    private ModeEnum getModeEnum(Object msg) {
        if (msg instanceof DataDto) {
            return ModeEnum.REQUEST;
        }

        if (msg instanceof DataRespDto) {
            return ModeEnum.RESPONSE;
        }
        throw new RuntimeException("there is no protof mode from current request data");
    }
}
